﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using InsideDL.MISService;
using InsideDL.MISControl;
using InsideDL.MISData;
using System.Diagnostics;
using System.IO;
using System.Net;
using System.Configuration;

namespace InsideDL
{
    public partial class frmMIS001 : MISControl.frmMatrix
    {
        //protected WebClient wbClient = null;
        protected string[] xlsCollect = null;
        public frmMIS001()
        {
            InitializeComponent();
            ucExecute1.ExecuteClick += new EventHandler(ucClickFacade);
            ucExecute_Exit.ExecuteClick += new EventHandler(ucClickFacade);
            this.controlList = new List<ucSelFileOrPath>
            {
                ucFilePath,ucDownload1,ucDownload2
            };
            ucDownload1.Txt = @"http://www.banking.gov.tw/ch/home.jsp?id=157&parentpath=0,4&mcustomize=bstatistics_view.jsp&serno=201105120014";
            ucDownload2.Txt = @"http://www.banking.gov.tw/ch/home.jsp?id=169&parentpath=0,2&mcustomize=news_view.jsp&dataserno=201203290003&aplistdn=ou=news,ou=multisite,ou=chinese,ou=ap_root,o=fsc,c=tw&toolsflag=Y";
            xlsCollect = ConfigurationManager.AppSettings["MIS001"]
                .ToString().Split(',');

        }

        protected override void execute()
        {
            if (base.Vaildation().Equals(false))
            {                 
                return; 
            }
            downloadFile1();
            downloadFile2();
            //downloadFile3(); 考慮到PDF 的問題，先暫時不做            
        }

        /// <summary>
        /// download 金融業務統計輯要
        /// http://www.banking.gov.tw/ch/home.jsp?id=157&parentpath=0,4
        /// 十數個檔案
        /// </summary>
        protected void downloadFile1()
        {
            ucBrowser1.NavigateURL(ucDownload1.Txt);
            HtmlElement html = ucBrowser1.GetElementByID("fontcontent");
            try
            {
                HtmlElementCollection pCollect = html.GetElementsByTagName("p");
                HtmlElementCollection aCollect = pCollect[1].GetElementsByTagName("a");
                int i = 0;
                foreach (HtmlElement ae in aCollect)
                {
                    string[] href = ae.GetAttribute("href").Split('/');
                    string result = Array.Find<string>(xlsCollect
                        , s => s.Equals(href[href.Length-1]));
                    if (!string.IsNullOrEmpty(result))
                    {
                        getFileFromWeb(ae.GetAttribute("href"), result);
                    }
                  
                    //Console.Write(ae.GetAttribute("title"));
                    i++;
                }
            }
            catch (Exception ex)
            {
                Console.Write(ex.Message);
            }
        }

        /// <summary>
        /// 新聞稿中找XXX年XX月份信用卡現金卡相關業務
        /// http://www.banking.gov.tw/ch/home.jsp?id=169&parentpath=0,2
        /// 信用卡現金卡
        /// </summary>
        protected void downloadFile2()
        {
            ucBrowser1.NavigateURL(ucDownload2.Txt);
            HtmlElement tbl01 = ucBrowser1.GetElementByID("___01");
            HtmlElementCollection trs = tbl01.GetElementsByTagName("tr");
            HtmlElement ae = trs[29].GetElementsByTagName("a")[0];
            string xls = string.Format("{0}.xls",ae.GetAttribute("title"));
            getFileFromWeb(ae.GetAttribute("href"), xls);
            ae = trs[34].GetElementsByTagName("a")[0];
            xls = string.Format("{0}.xls",ae.GetAttribute("title"));
            getFileFromWeb(ae.GetAttribute("href"), xls);
        }

        /// <summary>
        /// 金融機構一覽表這是PDF檔
        /// </summary>
        protected void downloadFile3()
        { }

        protected string getSaveFilePath(string p_file)
        {
          return System.IO.Path.Combine(ucFilePath.Txt, p_file);
        }

        protected void getFileFromWeb(string p_url, string p_file)
        {
            WebClient wbClient = new WebClient();
            wbClient.Headers.Add("Accept: text/html, application/xhtml+xml, */*");
            wbClient.Headers.Add("User-Agent: Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; WOW64; Trident/5.0)");

            wbClient.DownloadFile(p_url,getSaveFilePath(p_file));
            while (wbClient.IsBusy)
            {
                System.Threading.Thread.Sleep(1000);
            }

        }
    }
}
 